<template>
  <div class="werewolf-room">
    <div class="room-header">
      <div class="room-info">
        <div class="room-avatar">🎭</div>
        <div class="room-details">
          <div class="room-title">
            <span class="game-icon">⏰</span>
            <span>{{ theaterData.title }}</span>
          </div>
          <div class="room-status">
            <span class="status-item phase">
              <span class="status-dot"></span>
              {{ currentNodeData.title }}
            </span>
            <span class="status-item">👥 {{ allCharacters.length }}个角色</span>
            <span class="status-item">🎬 {{ playerCharacter.name }}发言中</span>
            <span class="status-item" v-if="sessionId">🔗 已连接</span>
          </div>
        </div>
      </div>
      <div class="room-actions">
        <button class="action-btn secondary">
          <span class="icon">⚙️</span>
          <span>保存</span>
        </button>
        <button class="action-btn secondary">
          <span class="icon">📖</span>
          <span>剧情</span>
        </button>
        <button class="action-btn primary">
          <span class="icon">⏭️</span>
          <span>跳过发言</span>
        </button>
      </div>
    </div>
    <div class="main-content">
      <div class="speech-area">
        <div class="current-speaker-stage">
          <div class="script-section">
            <div class="script-header">
              <span class="script-icon">📜</span>
              <span class="script-title">{{ currentNodeData.title }}</span>
            </div>
            <div class="script-content">
              <div class="script-description" v-html="currentNodeData.content"></div>

              <!-- 当前玩家角色信息 -->
              <div class="player-role-info">
                <div class="roles-title">您扮演的角色：</div>
                <div class="current-role">
                  <div class="role-avatar">
                    <img :src="playerCharacter.avatar" :alt="playerCharacter.name" />
                  </div>
                  <div class="role-details">
                    <div class="role-name">{{ playerCharacter.name }}</div>
                    <div class="role-desc">{{ playerCharacter.description }}</div>
                    <div class="role-skills">
                      <span class="skills-label">技能：</span>
                      <div class="skills-list">
                        <span
                          v-for="skill in playerSkills.slice(0, 8)"
                          :key="skill"
                          class="skill-tag"
                        >
                          {{ skill }}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧当前发言角色区域 -->
          <div class="speaker-section">
            <div class="text-mode-section">
              <div class="speaker-info">
                <div class="speaker-avatar">
                  <img :src="playerCharacter.avatar" :alt="playerCharacter.name" />
                  <div class="role-indicator">🎭</div>
                </div>
                <div class="speaker-details">
                  <div class="speaker-name">{{ playerCharacter.name }}</div>
                  <div class="speaker-role"></div>
                  <div class="speech-status">
                    <span>文字发言模式</span>
                  </div>
                </div>
              </div>

              <div class="text-input-area">
                <div class="input-header">
                  <span class="input-icon">✍️</span>
                  <span class="input-title">输入您的发言内容</span>
                </div>
                <textarea
                  placeholder="请输入角色发言内容..."
                  class="text-input"
                  rows="4"
                ></textarea>
                <div class="input-footer">
                  <span class="input-tip">Ctrl + Enter 快速发送</span>
                  <button class="send-message-btn">
                    <span class="btn-icon">📤</span>
                    <span>发送</span>
                  </button>
                </div>
              </div>

              <!-- 等待状态 -->
              <div class="waiting-area">
                <div class="waiting-icon">⏳</div>
                <div class="waiting-text">等待xxx 发言</div>
                <div class="waiting-subtitle">请耐心等待轮到您...</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button class="action-button dialogue-btn text-mode">
            <span class="btn-icon">✍️</span>
            <span>文字模式</span>
          </button>

          <button class="action-button next-btn">
            <span class="btn-icon">➡️</span>
            <span>下一位</span>
          </button>
        </div>
      </div>
      <div class="sidebar">
        <!-- 发言顺序 -->
        <div class="speaking-order-panel">
          <div class="panel-header">
            <span class="panel-title">
              <span class="icon">🎯</span>
              <span>发言顺序</span>
            </span>
            <span class="turn-count">第{{ currentTurn }}轮</span>
          </div>
          <div class="order-list">
            <div
              v-for="(character, index) in speakingOrder"
              :key="character.id"
              :class="[
                'order-item',
                {
                  current: index === currentSpeakerIndex,
                  finished: index < currentSpeakerIndex,
                  upcoming: index > currentSpeakerIndex,
                },
              ]"
            >
              <div class="order-number">{{ index + 1 }}</div>
              <div class="order-avatar">
                <img :src="character.avatar" :alt="character.name" />
                <div class="order-status" v-if="index === currentSpeakerIndex">🎤</div>
                <div class="order-status finished" v-else-if="index < currentSpeakerIndex">✅</div>
              </div>
              <div class="order-info">
                <div class="order-name">{{ character.name }}</div>
                <div class="order-role">{{ getCharacterRole(character) }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 对话记录 -->
        <div class="chat-panel">

        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick, watch, onBeforeUnmount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const route = useRoute()

// 🔧 API客户端配置
const theaterDetailApiClient = axios.create({
  baseURL: 'http://localhost:8803',
  timeout: 30000,
})

const chatApiClient = axios.create({
  baseURL: 'http://127.0.0.1:8801',
  timeout: 30000,
})

// 类型定义
interface Character {
  id: string
  name: string
  description: string
  avatar: string
  selectedSkills?: string[]
}

interface ChatMessage {
  id: string
  character_id: string
  character_name: string
  message: string
  timestamp: string
  message_type: string
}

interface TheaterData {
  title: string
  description: string
  era: string
  location: string
  author: string
}

interface NodeData {
  id: string
  title: string
  content: string
  characterSettings: any
}

interface TheaterDetailData {
  theater_info: TheaterData
  script_nodes: NodeData[]
  characters: Character[]
  available_skills: string[]
}

// 响应式数据
const isLoading = ref(true)
const loadingText = ref('正在加载剧场体验...')
const isProcessingMessage = ref(false)
const userReply = ref('')
const inputError = ref('')
const errorMessage = ref('')
const successMessage = ref('')
const sceneProgress = ref(10)

// UI状态
const showQuickReplies = ref(false)
const showSettingsModal = ref(false)
const showHistoryModal = ref(false)
const isInputFocused = ref(false)
const isSceneContentExpanded = ref(false)
const sidebarOpen = ref(false)

// 设置选项
const enableQuickReplies = ref(true)
const autoScroll = ref(true)
const showSceneContent = ref(true)
const showInputTips = ref(true)

// 会话相关
const sessionId = ref<string>('')
const taskId = ref<string>('')
const selectedCharacterId = ref<string>('')
const selectedNodeId = ref<string>('')
const chatMessages = ref<ChatMessage[]>([])
const sessionStartTime = ref<string>('')

// 剧场数据
const theaterData = reactive<TheaterData>({
  title: '',
  description: '',
  era: '',
  location: '',
  author: '',
})

const currentNodeData = reactive<NodeData>({
  id: '',
  title: '',
  content: '',
  characterSettings: {},
})

const playerCharacter = reactive<Character>({
  id: '',
  name: '',
  description: '',
  avatar: '',
  selectedSkills: [],
})

const allCharacters = ref<Character[]>([])
const recentlySpokeCharacters = ref<string[]>([])
const availableSkills = ref<string[]>([])

// DOM引用
const dialogueContainer = ref<HTMLElement | null>(null)
const messageInput = ref<HTMLTextAreaElement | null>(null)

// 快捷回复建议
const quickReplySuggestions = computed(() => {
  if (!enableQuickReplies.value) return []

  const suggestions = [
    '我明白了',
    '请继续',
    '有什么我可以帮助的吗？',
    '这很有趣',
    '让我想想...',
    '我同意你的看法',
  ]

  return suggestions.slice(0, 4)
})

// 计算属性
const canSubmit = computed(() => {
  return (
    userReply.value.trim().length > 0 &&
    userReply.value.length <= 500 &&
    !isProcessingMessage.value &&
    sessionId.value !== ''
  )
})

const playerMessageCount = computed(() => {
  return chatMessages.value.filter(
    (msg) => msg.character_id === playerCharacter.id && msg.message_type === 'dialogue',
  ).length
})

const playerSkills = computed(() => {
  const normalizeSkillsData = (rawSkills: any): string[] => {
    if (!rawSkills) return []

    if (Array.isArray(rawSkills)) {
      return rawSkills.filter((skill) => typeof skill === 'string' && skill.trim().length > 0)
    }

    if (typeof rawSkills === 'string') {
      try {
        const parsed = JSON.parse(rawSkills)
        return normalizeSkillsData(parsed)
      } catch {
        return rawSkills.trim() ? [rawSkills.trim()] : []
      }
    }

    if (typeof rawSkills === 'object') {
      if (rawSkills.skills && Array.isArray(rawSkills.skills)) {
        return rawSkills.skills.filter(
          (skill: any) => typeof skill === 'string' && skill.trim().length > 0,
        )
      }
      if (rawSkills.name && typeof rawSkills.name === 'string') {
        return [rawSkills.name.trim()]
      }
    }

    return []
  }

  return normalizeSkillsData(playerCharacter.selectedSkills)
})

const dialogueMessages = computed(() => {
  return chatMessages.value.filter((msg) => msg.message_type === 'dialogue')
})

// 监听器
watch(
  chatMessages,
  () => {
    if (autoScroll.value) {
      nextTick(() => {
        scrollToBottom()
      })
    }
  },
  { deep: true },
)

watch(isInputFocused, (focused) => {
  showQuickReplies.value = focused && enableQuickReplies.value
})

// 🔧 核心修改：从API加载剧场数据
const loadTheaterDataFromAPI = async () => {
  try {
    console.log('🎭 开始从API加载剧场数据')

    // 1. 从路由参数获取必要信息
    taskId.value = route.query.task_id as string
    selectedCharacterId.value = route.query.character_id as string
    selectedNodeId.value = route.query.node_id as string

    if (!taskId.value) {
      throw new Error('缺少必要的task_id参数')
    }

    if (!selectedCharacterId.value) {
      throw new Error('缺少必要的character_id参数')
    }

    if (!selectedNodeId.value) {
      throw new Error('缺少必要的node_id参数')
    }

    console.log('📋 路由参数:', {
      taskId: taskId.value,
      characterId: selectedCharacterId.value,
      nodeId: selectedNodeId.value,
    })

    // 2. 调用theater_detail API获取剧场数据
    loadingText.value = '正在获取剧场详情...'

    const response = await theaterDetailApiClient.get(`/theater/${taskId.value}`)

    if (!response.data.success) {
      throw new Error(response.data.message || '获取剧场数据失败')
    }

    const theaterDetailData: TheaterDetailData = response.data.data.data
    console.log('✅ 获取到剧场数据:', theaterDetailData)

    // 3. 更新剧场基本信息
    if (theaterDetailData.theater_info) {
      Object.assign(theaterData, theaterDetailData.theater_info)
      console.log('✅ 剧场信息更新完成')
    }

    // 4. 设置所有角色
    if (theaterDetailData.characters && Array.isArray(theaterDetailData.characters)) {
      allCharacters.value = theaterDetailData.characters
      console.log(`✅ 加载 ${allCharacters.value.length} 个角色`)

      // 5. 设置玩家角色
      const playerChar = allCharacters.value.find((char) => char.id === selectedCharacterId.value)
      if (playerChar) {
        Object.assign(playerCharacter, playerChar)
        console.log('✅ 玩家角色设置完成:', playerCharacter.name)
      } else {
        throw new Error(`未找到指定的角色: ${selectedCharacterId.value}`)
      }
    }

    // 6. 设置当前节点
    if (theaterDetailData.script_nodes && Array.isArray(theaterDetailData.script_nodes)) {
      const currentNode = theaterDetailData.script_nodes.find(
        (node) => node.id === selectedNodeId.value,
      )
      if (currentNode) {
        Object.assign(currentNodeData, currentNode)
        console.log('✅ 当前节点设置完成:', currentNodeData.title)
      } else {
        throw new Error(`未找到指定的节点: ${selectedNodeId.value}`)
      }
    }

    // 7. 设置可用技能
    if (theaterDetailData.available_skills && Array.isArray(theaterDetailData.available_skills)) {
      availableSkills.value = theaterDetailData.available_skills
      console.log(`✅ 加载 ${availableSkills.value.length} 个技能`)
    }

    console.log('🎉 剧场数据加载完成')
  } catch (error) {
    console.error('❌ 加载剧场数据失败:', error)
    showError(error instanceof Error ? error.message : '加载剧场数据失败')
    throw error
  }
}

// 生命周期和方法
onMounted(async () => {
  console.log('🎭 剧场体验页面开始加载')

  try {
    // 🔧 修改：完全从API加载数据
    await loadTheaterDataFromAPI()

    // 初始化聊天会话
    await initializeChatSession()

    // 加载完成
    isLoading.value = false

    console.log('🎉 剧场体验页面加载完成')
  } catch (error) {
    console.error('❌ 页面加载失败:', error)
    showError('页面加载失败，请重试')
    isLoading.value = false
  }
})

onBeforeUnmount(() => {
  clearError()
  clearSuccess()
})

const isAxiosError = (
  error: unknown,
): error is { code?: string; message?: string; response?: any } => {
  return error !== null && typeof error === 'object' && 'code' in error
}

// 会话初始化
const initializeChatSession = async () => {
  try {
    loadingText.value = '正在检查聊天服务连接...'

    // 首先检查服务健康状态
    try {
      const healthResponse = await chatApiClient.get('/health')
      if (!healthResponse.data.success) {
        throw new Error('聊天服务未就绪')
      }
    } catch (healthError) {
      console.error('❌ 聊天服务连接失败:', healthError)
      showError('无法连接到聊天服务，请确保后端服务已启动')
      throw new Error('聊天服务连接失败')
    }

    loadingText.value = '正在初始化对话会话...'

    const response = await chatApiClient.post('/chat/start', {
      theater_title: theaterData.title,
      node_id: currentNodeData.id,
      node_title: currentNodeData.title,
      node_content: currentNodeData.content,
      player_character_id: playerCharacter.id,
      all_characters: allCharacters.value,
      character_settings: currentNodeData.characterSettings,
    })

    if (response.data.success) {
      sessionId.value = response.data.data.session_id
      chatMessages.value = response.data.data.initial_messages || []
      sessionStartTime.value = new Date().toISOString()

      console.log('✅ 聊天会话初始化成功:', sessionId.value)
      showSuccess('会话初始化成功，可以开始对话了！')

      nextTick(() => {
        scrollToBottom()
      })
    } else {
      throw new Error(response.data.message || '初始化会话失败')
    }
  } catch (error) {
    console.error('❌ 初始化聊天会话失败:', error)

    // 🔧 修复：使用类型守卫函数安全处理错误
    if (isAxiosError(error)) {
      if (error.code === 'ERR_NETWORK') {
        showError('网络连接失败，请检查聊天服务是否启动')
      } else if (error.code === 'ECONNREFUSED') {
        showError('无法连接到聊天服务，请启动chat_api.py')
      } else {
        showError('初始化聊天失败，请检查网络连接')
      }
    } else if (error instanceof Error) {
      showError(`初始化失败: ${error.message}`)
    } else {
      showError('初始化聊天失败，请检查网络连接')
    }

    throw error
  }
}

// 消息发送
const submitReply = async () => {
  if (!canSubmit.value) {
    if (userReply.value.trim().length === 0) {
      inputError.value = '请输入回复内容'
    } else if (userReply.value.length > 500) {
      inputError.value = '回复内容不能超过500个字符'
    } else if (!sessionId.value) {
      inputError.value = '会话未初始化，请刷新页面'
    }
    return
  }

  const message = userReply.value.trim()
  userReply.value = ''
  isProcessingMessage.value = true
  clearError()

  // 重置输入框高度
  if (messageInput.value) {
    messageInput.value.style.height = 'auto'
  }

  try {
    const response = await chatApiClient.post('/chat/message', {
      session_id: sessionId.value,
      message: message,
    })

    if (response.data.success) {
      const newMessages = response.data.data.new_messages || []
      chatMessages.value.push(...newMessages)

      updateRecentlySpokeCharacters(newMessages)
      sceneProgress.value = Math.min(100, sceneProgress.value + 5)

      console.log('✅ 消息发送成功，收到', newMessages.length, '条回复')
    } else {
      throw new Error(response.data.message || '发送消息失败')
    }
  } catch (error) {
    console.error('❌ 发送消息失败:', error)
    showError('发送失败，请重试')
    userReply.value = message
  } finally {
    isProcessingMessage.value = false
  }
}

// 更新最近说话的角色
const updateRecentlySpokeCharacters = (newMessages: ChatMessage[]) => {
  const speakers = newMessages
    .filter((msg) => msg.message_type === 'dialogue' && msg.character_id !== playerCharacter.id)
    .map((msg) => msg.character_id)

  recentlySpokeCharacters.value = [
    ...new Set([...speakers, ...recentlySpokeCharacters.value]),
  ].slice(0, 3)
}

// 工具方法
const getCharacterAvatar = (characterId: string) => {
  if (characterId === 'system') {
    return 'https://ui-avatars.com/api/?name=系统&background=6b7280&color=fff'
  }

  const character = allCharacters.value.find((c) => c.id === characterId)
  return character?.avatar || 'https://ui-avatars.com/api/?name=Unknown&background=ef4444&color=fff'
}

const getCharacterStatus = (characterId: string) => {
  if (characterId === playerCharacter.id) return 'player'
  if (recentlySpokeCharacters.value.includes(characterId)) return 'active'
  return 'idle'
}

const getCharacterStatusIcon = (characterId: string) => {
  const status = getCharacterStatus(characterId)
  const icons = {
    player: 'icon-user',
    active: 'icon-message',
    idle: 'icon-sleep',
  }
  return icons[status] || icons.idle
}

const getCharacterMessageCount = (characterId: string) => {
  return chatMessages.value.filter(
    (msg) => msg.character_id === characterId && msg.message_type === 'dialogue',
  ).length
}

const formatTime = (timestamp: string) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
  })
}

const formatSessionTime = () => {
  if (!sessionStartTime.value) return '未知'
  const date = new Date(sessionStartTime.value)
  return date.toLocaleString('zh-CN')
}

const scrollToBottom = () => {
  if (dialogueContainer.value) {
    dialogueContainer.value.scrollTop = dialogueContainer.value.scrollHeight
  }
}

// 输入处理
const clearInputError = () => {
  inputError.value = ''
}

const onInputFocus = () => {
  isInputFocused.value = true
}

const onInputBlur = () => {
  setTimeout(() => {
    isInputFocused.value = false
  }, 200)
}

const insertQuickReply = (text: string) => {
  if (userReply.value) {
    userReply.value += ' ' + text
  } else {
    userReply.value = text
  }

  if (messageInput.value) {
    messageInput.value.focus()
    messageInput.value.setSelectionRange(userReply.value.length, userReply.value.length)
  }

  nextTick(() => {
    adjustTextareaHeight()
  })
}

const insertNewLine = () => {
  userReply.value += '\n'
  nextTick(() => {
    adjustTextareaHeight()
  })
}

const adjustTextareaHeight = () => {
  const textarea = messageInput.value
  if (textarea) {
    textarea.style.height = 'auto'
    textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'
  }
}

const toggleSceneContent = () => {
  isSceneContentExpanded.value = !isSceneContentExpanded.value
}

const toggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value
}

// 🔧 修改：移除localStorage的保存逻辑
const saveProgress = async () => {
  try {
    // 不再保存到localStorage，只显示提示信息
    showSuccess('进度已自动保存到服务器')
    console.log('✅ 进度保存提示完成（数据已实时同步到服务器）')
  } catch (error) {
    console.error('保存进度提示失败:', error)
    showError('保存进度失败')
  }
}

const showHistory = () => {
  showHistoryModal.value = true
}

const closeHistory = () => {
  showHistoryModal.value = false
}

const resetScene = async () => {
  if (!confirm('确定要重置当前场景吗？这将清除所有对话记录。')) {
    return
  }

  try {
    chatMessages.value = []
    recentlySpokeCharacters.value = []
    sceneProgress.value = 10
    sessionId.value = ''

    await initializeChatSession()
    showSuccess('场景已重置')
  } catch (error) {
    console.error('重置场景失败:', error)
    showError('重置场景失败')
  }
}

const changeCharacter = () => {
  if (confirm('确定要切换角色吗？当前进度已自动保存到服务器。')) {
    router.push('/TheaterList')
  }
}

const exitExperience = () => {
  if (confirm('确定要退出剧场体验吗？当前进度已自动保存到服务器。')) {
    router.push('/TheaterList')
  }
}

// UI控制方法
const goBack = () => {
  if (chatMessages.value.length > 1) {
    if (confirm('确定要离开吗？当前进度已自动保存到服务器。')) {
      router.push('/TheaterList')
    }
  } else {
    router.push('/TheaterList')
  }
}

const openSettings = () => {
  showSettingsModal.value = true
}

const closeSettings = () => {
  showSettingsModal.value = false
}

// 消息提示
const showError = (message: string) => {
  errorMessage.value = message
  setTimeout(() => {
    errorMessage.value = ''
  }, 5000)
}

const showSuccess = (message: string) => {
  successMessage.value = message
  setTimeout(() => {
    successMessage.value = ''
  }, 3000)
}

const clearError = () => {
  errorMessage.value = ''
}

const clearSuccess = () => {
  successMessage.value = ''
}
</script>

<style scoped>
/* 样式部分保持不变，只添加一些新的样式 */
.werewolf-room {
  min-height: 94vh;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(6, 182, 212, 0.05) 100%);
  padding: 3vh 5vw;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  color: #1e293b;
  position: relative;
}

.werewolf-room::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    135deg,
    rgba(248, 250, 252, 0.95) 0%,
    rgba(241, 245, 249, 0.95) 50%,
    rgba(248, 250, 252, 0.95) 100%
  );
  z-index: -1;
}

/* 顶部房间信息栏 */
.room-header {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(59, 130, 246, 0.1);
  border-radius: 16px;
  padding: 16px 20px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.08);
}

.room-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.room-avatar {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.8) 0%, rgba(6, 182, 212, 0.8) 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
}

.room-title {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 4px;
}

.room-status {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #64748b;
}

.status-item.phase {
  color: rgba(6, 182, 212, 0.8);
  font-weight: 500;
}

.status-dot {
  width: 6px;
  height: 6px;
  background: rgba(6, 182, 212, 0.8);
  border-radius: 50%;
  animation: pulse-dot 2s infinite;
}

.room-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  border-radius: 10px;
  border: none;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn.secondary {
  background: rgba(59, 130, 246, 0.08);
  color: #475569;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.action-btn.secondary:hover:not(:disabled) {
  background: rgba(59, 130, 246, 0.12);
  border-color: rgba(59, 130, 246, 0.3);
}

.action-btn.primary {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.8) 0%, rgba(6, 182, 212, 0.8) 100%);
  color: white;
}

.action-btn.primary:hover:not(:disabled) {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.9) 0%, rgba(6, 182, 212, 0.9) 100%);
}

.action-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
  background: rgba(156, 163, 175, 0.3) !important;
  color: #9ca3af !important;
  border-color: rgba(156, 163, 175, 0.2) !important;
}

/* 主内容区域 */
.main-content {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 16px;
}

/* 左侧发言区域 */
.speech-area {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.current-speaker-stage {
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(59, 130, 246, 0.15);
  border-radius: 20px;
  padding: 24px;
  display: flex;
  gap: 24px;
  box-shadow: 0 8px 32px rgba(59, 130, 246, 0.08);
}

/* 左侧剧情内容区域 */
.script-section {
  flex: 1;
  min-width: 0;
}

.script-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(59, 130, 246, 0.15);
}

.script-icon {
  font-size: 18px;
}

.script-title {
  font-size: 18px;
  font-weight: 600;
  color: rgba(6, 182, 212, 0.9);
}

.script-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.script-description {
  font-size: 14px;
  color: #475569;
  line-height: 1.6;
  max-height: 300px;
  overflow-y: auto;
  padding-right: 8px;
}

.script-description::-webkit-scrollbar {
  width: 4px;
}

.script-description::-webkit-scrollbar-track {
  background: rgba(59, 130, 246, 0.08);
}

.script-description::-webkit-scrollbar-thumb {
  background: rgba(59, 130, 246, 0.3);
  border-radius: 2px;
}

.player-role-info {
  background: rgba(59, 130, 246, 0.06);
  border-radius: 12px;
  padding: 12px;
  border: 1px solid rgba(59, 130, 246, 0.15);
}

.roles-title {
  font-size: 13px;
  font-weight: 600;
  color: rgba(59, 130, 246, 0.8);
  margin-bottom: 8px;
}

.current-role {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.role-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  border: 2px solid rgba(59, 130, 246, 0.2);
}

.role-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.role-details {
  flex: 1;
}

.role-name {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 4px;
}

.role-desc {
  font-size: 12px;
  color: #64748b;
  line-height: 1.4;
  margin-bottom: 8px;
}

.role-skills {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.skills-label {
  font-size: 11px;
  color: #64748b;
}

.skills-list {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.skill-tag {
  background: rgba(59, 130, 246, 0.12);
  color: rgba(59, 130, 246, 0.8);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: 500;
}

/* 右侧发言角色区域 */
.speaker-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  min-width: 200px;
}

/* 文字模式样式 */
.text-mode-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
}

.text-input-area {
  background: rgba(59, 130, 246, 0.04);
  border-radius: 12px;
  padding: 16px;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.input-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.input-icon {
  font-size: 16px;
}

.input-title {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
}

.text-input {
  width: 100%;
  min-height: 80px;
  padding: 12px;
  border: 1px solid rgba(59, 130, 246, 0.2);
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
  outline: none;
  background: rgba(255, 255, 255, 0.8);
  color: #1e293b;
  font-family: inherit;
}

.text-input::placeholder {
  color: #64748b;
}

.text-input:focus {
  border-color: rgba(59, 130, 246, 0.4);
  background: rgba(255, 255, 255, 0.9);
}

.text-input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.input-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.input-tip {
  font-size: 11px;
  color: #64748b;
}

.send-message-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.8) 0%, rgba(6, 182, 212, 0.8) 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.send-message-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.9) 0%, rgba(6, 182, 212, 0.9) 100%);
}

.send-message-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.waiting-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 20px;
  background: rgba(59, 130, 246, 0.04);
  border-radius: 12px;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.waiting-icon {
  font-size: 24px;
}

.waiting-text {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.waiting-subtitle {
  font-size: 12px;
  color: #94a3b8;
  text-align: center;
}

/* 语音模式样式（保持原有样式） */
.voice-mode-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  width: 100%;
}

.speaker-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  text-align: center;
}

.speaker-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  border: 3px solid rgba(59, 130, 246, 0.3);
  overflow: hidden;
  transition: all 0.3s ease;
}

.speaker-avatar.is-speaking {
  border-color: rgba(6, 182, 212, 0.8);
  box-shadow: 0 0 20px rgba(6, 182, 212, 0.3);
}

.speaker-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.role-indicator {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  background: rgba(59, 130, 246, 0.8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: white;
}

.speaking-pulse {
  position: absolute;
  top: -6px;
  left: -6px;
  right: -6px;
  bottom: -6px;
  border: 2px solid rgba(6, 182, 212, 0.8);
  border-radius: 50%;
  animation: pulse-ring 2s infinite;
}

@keyframes pulse-ring {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  100% {
    transform: scale(1.2);
    opacity: 0;
  }
}

.speaker-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.speaker-name {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.speaker-role {
  font-size: 12px;
  color: rgba(59, 130, 246, 0.7);
}

.speech-status {
  font-size: 11px;
  color: #64748b;
}

.speech-timer {
  display: flex;
  align-items: center;
  justify-content: center;
}

.timer-circle {
  position: relative;
  width: 80px;
  height: 80px;
}

.timer-svg {
  width: 100%;
  height: 100%;
  transform: rotate(-90deg);
}

.timer-progress {
  transition: stroke-dashoffset 1s linear;
  stroke: rgba(6, 182, 212, 0.8);
}

.timer-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

/* 语音控制 */
.voice-controls {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.voice-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border-radius: 12px;
  border: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.8) 0%, rgba(5, 150, 105, 0.8) 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
}

.voice-btn.recording {
  background: linear-gradient(135deg, rgba(239, 68, 68, 0.8) 0%, rgba(220, 38, 38, 0.8) 100%);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2);
  animation: recording-pulse 1s infinite;
}

.voice-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

@keyframes recording-pulse {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

.voice-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(59, 130, 246, 0.08);
  border-radius: 12px;
  font-size: 12px;
  color: #64748b;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border-radius: 12px;
  border: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.dialogue-btn {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.8) 0%, rgba(29, 78, 216, 0.8) 100%);
  color: white;
  border: 2px solid transparent;
}

.dialogue-btn.text-mode {
  background: linear-gradient(135deg, rgba(79, 70, 229, 0.8) 0%, rgba(99, 102, 241, 0.8) 100%);
  border-color: rgba(79, 70, 229, 0.3);
}

.dialogue-btn.voice-mode {
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.8) 0%, rgba(5, 150, 105, 0.8) 100%);
  border-color: rgba(16, 185, 129, 0.3);
}

.end-turn-btn {
  background: linear-gradient(135deg, rgba(245, 158, 11, 0.8) 0%, rgba(217, 119, 6, 0.8) 100%);
  color: white;
}

.next-btn {
  background: linear-gradient(135deg, rgba(5, 150, 105, 0.8) 0%, rgba(4, 120, 87, 0.8) 100%);
  color: white;
}

.action-button:disabled {
  opacity: 0.4;
  cursor: not-allowed;
  background: rgba(156, 163, 175, 0.3) !important;
  color: #9ca3af !important;
  border-color: rgba(156, 163, 175, 0.2) !important;
}

/* 右侧边栏 */
.sidebar {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.speaking-order-panel,
.chat-panel {
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(59, 130, 246, 0.15);
  border-radius: 16px;
  padding: 16px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.panel-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
}

.turn-count {
  background: rgba(59, 130, 246, 0.12);
  color: rgba(59, 130, 246, 0.8);
  padding: 4px 8px;
  border-radius: 8px;
  font-size: 11px;
  font-weight: 500;
}

.message-count {
  background: rgba(16, 185, 129, 0.12);
  color: rgba(16, 185, 129, 0.8);
  padding: 4px 8px;
  border-radius: 8px;
  font-size: 11px;
  font-weight: 500;
}

/* 发言顺序列表 */
.order-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.order-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.2s;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.order-item.current {
  background: rgba(6, 182, 212, 0.1);
  border-color: rgba(6, 182, 212, 0.2);
}

.order-item.finished {
  opacity: 0.6;
  background: rgba(16, 185, 129, 0.08);
}

.order-item.upcoming {
  opacity: 0.8;
}

.order-number {
  width: 20px;
  height: 20px;
  background: rgba(59, 130, 246, 0.15);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  font-weight: 600;
  flex-shrink: 0;
  color: rgba(59, 130, 246, 0.8);
}

.order-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  flex-shrink: 0;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.order-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.order-status {
  position: absolute;
  top: -4px;
  right: -4px;
  width: 16px;
  height: 16px;
  background: rgba(59, 130, 246, 0.8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 8px;
  color: white;
}

.order-status.finished {
  background: rgba(16, 185, 129, 0.8);
}

.order-info {
  flex: 1;
  min-width: 0;
}

.order-name {
  font-size: 12px;
  font-weight: 500;
  color: #1e293b;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.order-role {
  font-size: 10px;
  color: #64748b;
}

/* 聊天区域 */
.chat-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.chat-messages {
  flex: 1;
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 12px;
  padding-right: 4px;
}

.chat-messages::-webkit-scrollbar {
  width: 3px;
}

.chat-messages::-webkit-scrollbar-track {
  background: rgba(59, 130, 246, 0.08);
}

.chat-messages::-webkit-scrollbar-thumb {
  background: rgba(59, 130, 246, 0.3);
  border-radius: 2px;
}

.game-message {
  margin-bottom: 8px;
  padding: 8px;
  border-radius: 8px;
  font-size: 12px;
  line-height: 1.4;
}

.game-message.system {
  background: rgba(6, 182, 212, 0.1);
  border: 1px solid rgba(6, 182, 212, 0.2);
}

.game-message.dialogue {
  background: rgba(59, 130, 246, 0.1);
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.game-message.own-message {
  background: rgba(59, 130, 246, 0.15);
  border: 1px solid rgba(59, 130, 246, 0.3);
}

.message-time {
  font-size: 10px;
  color: #64748b;
  margin-bottom: 2px;
}

.message-player {
  font-weight: 600;
  color: rgba(6, 182, 212, 0.8);
}

.message-text {
  color: #475569;
}

/* 消息提示样式 */
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  background: white;
  border-radius: 12px;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  animation: slideIn 0.3s ease;
  max-width: 400px;
}

.toast-error {
  border-left: 4px solid #ef4444;
}

.toast-success {
  border-left: 4px solid #10b981;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  color: #6b7280;
  padding: 0;
  margin-left: auto;
}

.close-btn:hover {
  color: #374151;
}

/* 加载状态样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  backdrop-filter: blur(4px);
}

.loading-spinner {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f4f6;
  border-top: 3px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes pulse-dot {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    grid-template-columns: 1fr;
  }

  .sidebar {
    order: -1;
  }

  .current-speaker-stage {
    flex-direction: column;
    gap: 16px;
  }

  .speaker-section {
    min-width: auto;
  }
}

@media (max-width: 768px) {
  .werewolf-room {
    padding: 12px;
  }

  .room-header {
    flex-direction: column;
    gap: 12px;
    padding: 12px 16px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .current-role {
    flex-direction: column;
    text-align: center;
  }
}
</style>
